import os
import sys
import cv2

'''
图片拼接程序
'''
def pinjie(image1_path,image2_path,out_name):
    img1 = cv2.imread(image1_path)
    img2 = cv2.imread(image2_path)
    stitcher = cv2.Stitcher.create(cv2.Stitcher_PANORAMA)

    (status, pano) = stitcher.stitch((img1, img2))
    if status != cv2.Stitcher_OK:
        print("不能拼接图片, error code = %d" % status)
        sys.exit(-1)
    print("拼接成功.")
    cv2.imwrite(out_name, pano)
    cv2.waitKey(0)

def full_view(angle_pic1,angle_pic2,angle_pic3,angle_pic4,angle_pic5,angle_pic6):
    file_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))+r'/join_pic'
    pinjie(angle_pic1, angle_pic2,os.path.join(file_path,'12.jpg'))

    pinjie(angle_pic4,angle_pic5, os.path.join(file_path,"45.jpg"))
    immg1 = cv2.imread(os.path.join(file_path,"45.jpg"))
    immg1 = immg1[:, 0:1350]
    cv2.imwrite(os.path.join(file_path,'45.jpg'), immg1)
    pinjie(os.path.join(file_path,'12.jpg'), angle_pic3, os.path.join(file_path,'123.jpg'))
    pinjie(os.path.join(file_path,'45.jpg'), angle_pic6, os.path.join(file_path,'456.jpg'))
    # 对拼接成功的三张图片进行裁剪处理
    imag123 = cv2.imread(os.path.join(file_path,'123.jpg'))
    imag456 = cv2.imread(os.path.join(file_path,'456.jpg'))
    imag123 = imag123[:1740, :1920]
    imag456 = imag456[:1740, :1920]
    cv2.imwrite(os.path.join(file_path,'123.jpg'), imag123)
    cv2.imwrite(os.path.join(file_path,'456.jpg'), imag456)
    # 生成全景图片
    pinjie(os.path.join(file_path,'123.jpg'), os.path.join(file_path,'456.jpg'), os.path.join(file_path,'full_view.jpg'))

    cv2.waitKey(0)

def run_stitch(window):
    tree_images_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) + r'\tree_images'
    path_list = os.listdir(tree_images_path)
    angle1 = os.path.join(tree_images_path, path_list[0])
    angle2 = os.path.join(tree_images_path, path_list[1])
    angle3 = os.path.join(tree_images_path, path_list[2])
    angle4 = os.path.join(tree_images_path, path_list[3])
    angle5 = os.path.join(tree_images_path, path_list[4])
    angle6 = os.path.join(tree_images_path, path_list[5])
    full_view(angle1, angle2, angle3, angle4, angle5, angle6)
    # 完成拼接后写入一个标志与主窗口通信让他知道你已经执行完了
    window.write_event_value('-THREAD-','*** The thread says.... "I am finished" ***')

if __name__ == "__main__":
    pass
    # pinjie(r'C:\Users\zh006\Desktop\大创\ROS上位机界面控制\tree_images\11.jpg',r'C:\Users\zh006\Desktop\大创\ROS上位机界面控制\tree_images\22.jpg','12.jpg')

